/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.servico;

import br.com.foxinline.enums.TipoLogradouro;
import br.com.foxinline.modelo.Bairro;
import br.com.foxinline.modelo.Dne;
import br.com.foxinline.modelo.Endereco;
import br.com.foxinline.utilitario.Caracter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 *
 * @author laverson
 */
@Stateless
public class DneServico extends ServicoGenerico<Dne> {

    @EJB
    CidadeServico cityService;
    @EJB
    BairroServico bairroService;

    public DneServico() {
        super(Dne.class);
    }

    @Override
    public void salvar(Dne entity) {
        entity.setCep(Caracter.removecaracter(entity.getCep()));
        entity.setDataAtualizacao(new Date());
        entity.setAtivo(true);
        super.salvar(entity);
    }

    @Override
    public void deletar(Dne entity) {
        entity.setDataAtualizacao(new Date());
        entity.setAtivo(false);
        atualizar(entity);
    }

    @Override
    public void atualizar(Dne entity) {
        entity.setCep(Caracter.removecaracter(entity.getCep()));
        entity.setDataAtualizacao(new Date());
        super.atualizar(entity);
    }

    private Dne fillFildes(Dne entity) {
        entity.setCep(Caracter.removecaracter(entity.getCep()));

        entity.setNomeclog(entity.getRua());

        for (TipoLogradouro type : Arrays.asList(TipoLogradouro.values())) {
            if (entity.getRua().toLowerCase().trim().startsWith(type.getNome().toLowerCase())) {
                entity.setNomeslog(entity.getRua().trim().substring(type.getNome().length() + 1));
            }
        }

        return entity;
    }

    public Endereco existCep(Endereco a) {
        a.setCep(Caracter.removecaracter(a.getCep()));

        Dne dne;
        String sql = "Select d from Dne d where d.cep like lower(:cep)";

        Query query = getEntityManager().createQuery(sql);
        query.setParameter("cep", a.getCep());
        try {
            dne = (Dne) query.getResultList().get(0);

        } catch (NoResultException nr) {
            return null;
        } catch (NonUniqueResultException nre) {
            return null;
        } catch (Exception e) {
            return null;
        }

        return dne != null ? dneToEndereco(dne) : null;
    }

    private Endereco dneToEndereco(Dne dne) {
        Endereco endereco = new Endereco();

        endereco.setCep(Caracter.removecaracter(dne.getCep()));
        endereco.setBairro(dne.getBairro());
        endereco.setLogradouro(dne.getNomeclog());

        return endereco;
    }

    /**
     *
     * @param findDne pesquisa
     */
    public List<Dne> findDne(Dne dne) {
        dne.setCep(Caracter.removecaracter(dne.getCep()));
        dne.setRua(dne.getRua().replace(" ", "%"));

        Bairro bairro = dne.getBairro();

        String sql = "select d from Dne d ";

        if (bairro != null) {
            if (bairro.getId() != null) {
                bairro = bairroService.pesquisar(bairro.getId());
                if ((bairro.getNome() != null) && (!bairro.getNome().equals(""))) {
                    sql += "JOIN d.bairro b ";
                }
            }
        }

        sql += " WHERE ";

        if ((dne.getCep() != null) && (!dne.getCep().equals(""))) {
            sql += " lower(d.cep) like lower(:cep) and ";
        }
        if ((dne.getRua() != null) && (!dne.getRua().equals(""))) {
            sql += " lower(d.rua) like lower(:patio) and ";
        }
        if (bairro != null) {
            if ((bairro.getNome() != null) && (!bairro.getNome().equals(""))) {
                sql += " lower(b.nome) like lower(:nomeBairro) and ";
            }
        }

        sql += " d.ativo = true and 1=1 ";
        Query query = getEntityManager().createQuery(sql);

        if ((dne.getCep() != null) && (!dne.getCep().equals(""))) {
            query.setParameter("cep", "%" + dne.getCep() + "%");
        }
        if ((dne.getRua() != null) && (!dne.getRua().equals(""))) {
            query.setParameter("patio", "%" + dne.getRua() + "%");
        }
        if ((bairro != null)) {
            if ((bairro.getNome() != null) && (!bairro.getNome().equals(""))) {
                query.setParameter("nomeBairro", "%" + bairro.getNome() + "%");
            }
        }

        return query.getResultList();
    }

    public List<String> getAllBairro() {
        String sql = "Select distinct b.nome from Dne d JOIN d.bairro b JOIN b.cidade c where "
                + " c.id = :cidadeID";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("cidadeID", 5658);

        return query.getResultList();
    }

    public List<Dne> getAllUpdate(Date date) {
        String sql = "Select d from Dne d where d.dataAtualizacao > :data";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("data", date);

        return query.getResultList();
    }
}
